<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="130px"
      v-loading="formLoading"
    >
      <el-form-item label="部门编码" prop="deptCode">
        <el-input v-model="formData.deptCode" placeholder="请输入部门编码" />
      </el-form-item>
      <el-form-item label="部门名称" prop="deptName">
        <el-input v-model="formData.deptName" placeholder="请输入部门名称" />
      </el-form-item>
      <el-form-item label="负责人" prop="configOrgStaffArchivesId">
        <el-select
          v-model="staffName"
          filterable
          remote
          placeholder="请选择负责人"
          value-key="id"
          :remote-method="remoteMethod"
          :loading="loading"
          @change="changeStaff"
        >
          <el-option
            v-for="item in options"
            :key="item.id"
            :label="item['staffName']"
            :value="item"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="所属事业部名称" prop="dictCauseName">
        <el-select v-model="formData.dictCauseName" placeholder="请选择事业部名称" @change="changeCause">
          <el-option
            v-for="dict in getStrDictOptions('config_cause_dept')"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="所属事业部代码" prop="dictCauseCode">
        <el-select v-model="formData.dictCauseCode" placeholder="请选择事业部代码" disabled>
          <el-option
            v-for="dict in getStrDictOptions('config_cause_dept')"
            :key="dict.value"
            :label="dict.value"
            :value="dict.label"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" type="textarea" placeholder="请输入备注" />
      </el-form-item>
      <el-form-item label="部门状态" prop="dictEnableStatus">
        <el-select v-model="formData.dictEnableStatus" placeholder="请选择部门状态">
          <el-option
            v-for="dict in getIntDictOptions('dict_enable_status')"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :loading="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getStrDictOptions, getIntDictOptions } from '@/utils/dict'
import * as OrgDeptArchivesApi from '@/api/config/orgDeptArchives'
import * as ComponentApi from '@/api/componentApi/index'
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const loading = ref(false) //负责人loading
const options = ref<OptionStaff[]>([])//负责人数据
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  deptCode: undefined,
  deptName: undefined,
  configOrgStaffArchivesId: undefined,
  configOrgStaffArchivesName: undefined,
  dictCauseName: undefined,
  dictCauseCode: undefined,
  remark: undefined,
  dictEnableStatus: undefined
})
const formRules = reactive({
  deptCode: [{ required: true, message: '部门档案编码不能为空', trigger: 'blur' }],
  deptName: [{ required: true, message: '部门档案名称不能为空', trigger: 'blur' }],
  dictCauseName: [{ required: true, message: '事业部名称不能为空', trigger: 'change' }],
  dictEnableStatus: [{ required: true, message: '部门状态不能为空', trigger: 'change' }]
})
const formRef = ref() // 表单 Ref

type OptionStaff = {
  id: number,
  staffName: string
}
const staffName = ref<OptionStaff>()

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
 
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await OrgDeptArchivesApi.getOrgDeptArchives(id)
      const item = {id:formData.value.configOrgStaffArchivesId, staffName:formData.value.configOrgStaffArchivesName}
      options.value = [item]
      staffName.value = {
        id: formData.value.configOrgStaffArchivesId,
        staffName: formData.value.configOrgStaffArchivesName
      }
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

// 负责人改变
const changeStaff = (val) => {
  formData.value.configOrgStaffArchivesId = val.id
  formData.value.configOrgStaffArchivesName = val.staffName
}

/**事业部改变 */
const changeCause = (val: string) => {
  console.log(val);
  formData.value.dictCauseCode = val
}
/**获取负责人 */
const remoteMethod = async (query: string) => {
  if (query) {
    loading.value = true
    try {
      let res = await ComponentApi.getStaffList(query);
      console.log(res, 1111111111111)
      options.value = res;
      console.log(options.value);
      loading.value = false
    } finally {
      loading.value = false
      //options.value = []
    }
  } else {
    options.value = []
  }
}
/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as OrgDeptArchivesApi.OrgDeptArchivesVO
    if (formType.value === 'create') {
      await OrgDeptArchivesApi.createOrgDeptArchives(data)
      message.success(t('common.createSuccess'))
    } else {
      await OrgDeptArchivesApi.updateOrgDeptArchives(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    deptCode: undefined,
    deptName: undefined,
    configOrgStaffArchivesId: undefined,
    configOrgStaffArchivesName: undefined,
    dictCauseName: undefined,
    dictCauseCode: undefined,
    remark: undefined,
    dictEnableStatus: undefined
  }
  formRef.value?.resetFields()
}
</script>